
package biblio.service.reader;


import biblio.bean.ReaderBean;
import biblio.dao.ReaderDAO;
import biblio.domain.Reader;
import biblio.exception.NoSuchEntityException;
import biblio.util.SourceName;
import biblio.util.interfaces.RequestOperationHelper;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;


/**
 *
 * @author mephisto
 */
@ManagedBean(name="readerService")
@ApplicationScoped
public class ReaderServiceImpl implements ReaderService
{
    public void create()
    {
        RequestOperationHelper rOH = (RequestOperationHelper)appContext.getBean("rOH");
        readerBean = (ReaderBean) rOH.getBean("readerBean");
        Reader reader = new Reader();
        reader.setFirstName(readerBean.getFirstName());
        reader.setLastName(readerBean.getLastName());
        reader.setAddress(readerBean.getAddress());
        reader.setCity(readerBean.getCity());
        reader.setEmail(readerBean.getEmail());
        reader.setZipCode(readerBean.getZipCode());

        ReaderDAO readerDAO = (ReaderDAO)appContext.getBean("readerDAO");
        readerDAO.create(reader);
        readerBean.clear();
    }

     public void update(Reader reader)
    {
        log.debug("Reader for update: " + reader.getId());

        ReaderDAO readerDAO = (ReaderDAO)appContext.getBean("readerDAO");
        try
        {
            readerDAO.update(reader);
        }
        catch (NoSuchEntityException ex)
        {
            log.error("Entity with id: " + reader.getId() + "does not exist in the database");
            log.error(ex.getMessage());
        }
    }

    public void delete(Reader reader)
    {
        ReaderDAO readerDAO = (ReaderDAO)appContext.getBean("readerDAO");
        try
        {
            readerDAO.delete(reader);
        }
        catch(DataAccessException e)
        {
            log.error("Entity with id: " + reader.getId() + "does not exist in the database");
            log.error(e);
        }
    }

    static
    {
        appContext = new ClassPathXmlApplicationContext( new String[] {
                SourceName.AUX_APPLICATION_CONTEXT,
                SourceName.DAO_APPLICATION_CONTEXT
        });
    }


    private static ApplicationContext appContext;
    private static Logger log = Logger.getLogger(ReaderServiceImpl.class);
    private ReaderBean readerBean;
}
